package com.geline.easytrans.config;

import com.geline.easytrans.dict.DictItem;
import com.geline.easytrans.dict.DictOptions;
import com.geline.easytrans.dict.IDict;
import com.geline.easytrans.dict.IDictUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 枚举字典　@DictType注册器
 *
 * @author: mengxin
 * @date: 2023/5/21 9:28
 */
@Slf4j
public class DictEnumRegistry {

    private static Map<String, List<DictOptions>> dictOptionsMap = new HashMap<>();
    private static Map<String, DictItem> dictItemMap = new HashMap<>();

    public static void putEnumClass(Class<? extends IDict> enumClass, String dictType, String dictName) {
        List<DictOptions> list = IDictUtil.toList(enumClass);
        if(list != null && !list.isEmpty()){
            dictOptionsMap.put(dictType, list);
            log.info("put {} [{}]", enumClass.getSimpleName(), dictType);
        }
        if(dictItemMap.get(dictType)!=null){
            log.warn("found more @DictType = {}", dictType);
        }
        dictItemMap.put(dictType, new DictItem(dictType, dictName));
    }

    public static void put(String dictType, List<DictOptions> optionsList) {
        dictOptionsMap.put(dictType, optionsList);
    }

    public static Map<String, List<DictOptions>> getDictOptionsMap() {
        return dictOptionsMap;
    }

    public static List<String> getDictTypeKeys() {
        return new ArrayList<>(dictItemMap.keySet());
    }

    public static List<DictItem> getDictItems() {
        return new ArrayList<>(dictItemMap.values());
    }

    public static List<DictOptions> getDictOptions(String dictType){
        return dictOptionsMap.get(dictType);
    }

    /**
     * 获取字典值对应的标签名
     * @param dictType
     * @param dictValue
     * @return
     */
    public static String getDictLabel(String dictType, Object dictValue){
        List<DictOptions> options = dictOptionsMap.get(dictType);
        if(options != null){
            for (DictOptions row : options){
                if(row.getDictValue().toString().equals(dictValue.toString())){
                    return row.getDictLabel();
                }
            }
        }
        return null;
    }

    /**
     * 获取字典值对应的标签名
     * @param dictType
     * @param dictLabel
     * @return
     */
    public static Object getDictValue(String dictType, String dictLabel){
        List<DictOptions> options = dictOptionsMap.get(dictType);
        if(options != null){
            for (DictOptions row : options){
                if(row.getDictLabel().equals(dictLabel)){
                    return row.getDictValue();
                }
            }
        }
        return null;
    }
}
